// pages/my-adoption/my-adoption.js
const { get, del } = require('../../utils/request')
const { formatDate, showSuccess, showError, showConfirm } = require('../../utils/util')

Page({
  data: {
    adoptionList: [],
    statusIndex: 0,
    statusList: ['全部状态', '待审核', '已通过', '已拒绝'],
    loading: false
  },

  onLoad() {
    this.loadAdoptionList()
  },

  onShow() {
    this.loadAdoptionList()
  },

  onPullDownRefresh() {
    this.loadAdoptionList(() => {
      wx.stopPullDownRefresh()
    })
  },

  // 加载领养申请列表
  loadAdoptionList(callback) {
    const app = getApp()
    if (!app.globalData.userInfo || !app.globalData.userInfo.id) {
      showError('请先登录')
      wx.navigateBack()
      return
    }

    this.setData({ loading: true })

    const params = {
      userId: app.globalData.userInfo.id
    }

    // 添加状态筛选
    if (this.data.statusIndex > 0) {
      params.status = this.data.statusList[this.data.statusIndex]
    }

    get('/adoption/list', params).then(res => {
      if (res && res.code === '200') {
        const adoptionList = res.data || []

        // 格式化时间
        adoptionList.forEach(item => {
          item.createTime = formatDate(item.createTime)
          if (item.reviewTime) {
            item.reviewTime = formatDate(item.reviewTime)
          }
        })

        this.setData({
          adoptionList
        })
      }
    }).catch(err => {
      console.error('加载领养申请列表失败:', err)
      // 如果是token过期，不显示错误提示，因为request.js已经处理了
      if (err && err.code !== '401') {
        showError('加载失败')
      }
    }).finally(() => {
      this.setData({ loading: false })
      callback && callback()
    })
  },

  // 状态筛选
  onStatusChange(e) {
    this.setData({
      statusIndex: parseInt(e.detail.value)
    })
    this.loadAdoptionList()
  },

  // 刷新
  onRefresh() {
    this.loadAdoptionList()
  },

  // 查看宠物详情
  viewPetDetail(e) {
    const petId = e.currentTarget.dataset.petId
    wx.navigateTo({
      url: `/pages/pet-detail/pet-detail?id=${petId}`
    })
  },

  // 取消申请
  async cancelApplication(e) {
    const id = e.currentTarget.dataset.id
    
    try {
      await showConfirm('确定要取消这个领养申请吗？')
    } catch {
      return
    }

    del(`/adoption/${id}`).then(res => {
      showSuccess('取消成功')
      this.loadAdoptionList()
    }).catch(err => {
      showError(err.msg || '取消失败')
    })
  },

  // 去申请领养
  goToAdopt() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  }
})
